<?php

namespace Iwester\Http\Controllers\Admin\Manage;

use Iwester\Http\Controllers\Admin\BaseController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;
use Iwester\Http\Model\Config\Banner;


class AdminBannerController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * banner 列表
     * @return Response
     */
    public function banner(Request $request)
    {
        $bannerCategories = Banner::select(['category_name','batch'])->groupBy(['category_name','batch'])->get();
        return view('iwester::admin.manage.banner.banner', [
            'bannerCategories'=> $bannerCategories
        ]);
    }

    /**
     * 添加Banner分类
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($batch, $id=0)
    {
        $batchItem = Banner::where('batch', $batch)->first();
        $banner = $id ? Banner::find($id) : false;
        return view('iwester::admin.manage.banner.edit', [
            'batchItem'=> $batchItem,
            'banner'=> $banner,
        ]);
    }

    /**
     * 保存Banner
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        try {
            \DB::beginTransaction();
            $id = $request->input('id', 0);
            $bannerParam = $request->get('banner', []);
            if ($id){
                $banner = Banner::find($id);
                if ($banner->category_name != $bannerParam['category_name']){
                    Banner::where('batch', $banner->batch)->update(['category_name'=> $bannerParam['category_name']]);
                }
                $banner->update($bannerParam);
            }else{
                Banner::create($bannerParam);
            }
            \DB::commit();
            return redirect(route('manage.banner'));
        } catch (\Exception $e) {
            \DB::rollBack();
            return  redirect()->route('manage.banner')->with('errors', ['系统错误，保存失败']);
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function destroy($batch, $id=0)
    {
        try {
            \DB::beginTransaction();
            if ($id){
                Banner::find($id)->delete();
            }else{
                Banner::where('batch', $batch)->delete();
            }
            \DB::commit();
            return ['code' => 200, 'message' => '删除成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }
}
